package org.markwebb.mina.playground.hbfilter.server;

import java.nio.charset.Charset;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.TransportType;
import org.apache.mina.transport.socket.nio.SocketSessionConfig;

public class HbHandler extends IoHandlerAdapter {

    @Override
    public void sessionCreated( IoSession session )
    {
        if( session.getTransportType() == TransportType.SOCKET )
        {
            ( ( SocketSessionConfig ) session.getConfig() ).setReceiveBufferSize( 2048 );
        }
        
        session.setIdleTime( IdleStatus.BOTH_IDLE, 10 );
        
       ByteBuffer hello = ByteBuffer.allocate(8);
       hello.put( Charset.defaultCharset().encode("Hello") );
       hello.flip();
       session.write( hello );
    }
    
    @Override
    public void sessionIdle( IoSession session, IdleStatus status )
    {
        System.out.println(
                "*** IDLE #" +
                session.getIdleCount( IdleStatus.BOTH_IDLE ) +
                " ***" );
    }

    @Override
    public void exceptionCaught( IoSession session, Throwable cause )
    {
        cause.printStackTrace();
        session.close();
    }

    @Override
    public void messageReceived( IoSession session, Object message ) throws Exception
    {
        if( !( message instanceof ByteBuffer ) )
        {
            return;
        }

        ByteBuffer rb = ( ByteBuffer ) message;
        // Write the received data back to remote peer
        ByteBuffer wb = ByteBuffer.allocate( rb.remaining() );
        wb.put( rb );
        wb.flip();
        session.write( wb );
    }
}
